#!/bin/sh

# Find all backlight control directories
# sort to have the same order than in es and other places
DISPLAYS=$(find /sys/class/backlight/* | sort 2>/dev/null | grep backlight)
CYCLESTEP=20 # % additional brightness at each step

if echo "${1}" | grep -qE "^-[0-9]$"
then
    NUM_DISPLAY=$1
    shift
    NDISPLAYS=$(echo "${DISPLAYS}" | wc -l)
    if test -${NDISPLAYS} -gt ${NUM_DISPLAY}
    then
	echo "brightness not found" >&2
	exit 1
    fi
    DISPLAYS=$(echo "${DISPLAYS}" | head ${NUM_DISPLAY} | tail -1)
fi

if [ -z "${DISPLAYS}" ]; then
    echo "no brightness found" >&2
    exit 1
fi

# Function to set the brightness for a specific display
setValue() {
    NEWVAL=$1
    XMAX=$2
    BRIGHTNESS_FILE=$3

    test "${NEWVAL}" -lt 0         && NEWVAL=0
    test "${NEWVAL}" -gt "${XMAX}" && NEWVAL="${XMAX}"
    
    echo "${NEWVAL}" > "${BRIGHTNESS_FILE}"
}

# Function to cycle the brightness for all displays
cycle() {
    # Base the cycle on the first display
    FIRST_D=$(echo "${DISPLAYS}" | head -n1)
    B="${FIRST_D}"/brightness
    XMAX=$(cat "${FIRST_D}"/max_brightness)

    X=$(cat "${B}")
    FVALUE=$(echo "scale=3;${X}" "*" "100" / "${XMAX}" | bc)
    LC_ALL=C FVALUE=$(printf '%.*f\n' 0 "${FVALUE}") # round
    NEWVAL_PERCENT=$(echo "${FVALUE} + ${CYCLESTEP}" | bc)
    [ "${NEWVAL_PERCENT}" -gt 100 ] && NEWVAL_PERCENT=0
    echo "Brightness cycling to ${NEWVAL_PERCENT}%"

    # Apply the new brightness to all displays
    for D in ${DISPLAYS}; do
        B="${D}"/brightness
        XMAX=$(cat "${D}"/max_brightness)
        NEWVAL=$(expr "${NEWVAL_PERCENT}" "*" "${XMAX}" / 100)
        setValue "${NEWVAL}" "${XMAX}" "${B}"
    done
    exit 0
}

# Get current brightness of the first display
if [ $# = 0 ]; then
    FIRST_D=$(echo "${DISPLAYS}" | head -n1)
    B="${FIRST_D}"/brightness
    XMAX=$(cat "${FIRST_D}"/max_brightness)
    X=$(cat "${B}")
    FVALUE=$(echo "scale=3;${X}" "*" "100" / "${XMAX}" | bc)
    LC_ALL=C printf '%.*f\n' 0 "${FVALUE}" # round
    exit 0
fi

# Set brightness for all displays
if [ $# = 1 ]; then
    if [ "${1}" = "cycle" ]; then
       cycle
    else
       for D in ${DISPLAYS}; do
           B="${D}"/brightness
           XMAX=$(cat "${D}"/max_brightness)
           NEWVAL=$(expr "${1}" "*" "${XMAX}" / 100)
           setValue "${NEWVAL}" "${XMAX}" "${B}"
       done
       exit 0
    fi
fi

# Increase or decrease brightness for all displays
if [ $# = 2 ]; then
    for D in ${DISPLAYS}; do
        B="${D}"/brightness
        XMAX=$(cat "${D}"/max_brightness)
        X=$(cat "${B}")
        DELTA=$(expr "${2}" '*' ${XMAX} / 100)
        NEWVAL=$(expr "${X}" "${1}" "${DELTA}")
        setValue "${NEWVAL}" "${XMAX}" "${B}"
    done
    exit 0
fi

# help
echo "${0}"      >&2
echo "${0} + 10" >&2
echo "${0} - 20" >&2
echo "${0} cycle" >&2
exit 1
